package com.ruoyi.web.controller.an;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.beust.jcommander.Strings;
import com.ruoyi.an.domain.AnWechatUser;
import com.ruoyi.an.service.IAnWechatUserService;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import static com.ruoyi.common.config.WeixinConfig.appid;
import static com.ruoyi.common.config.WeixinConfig.secret;


@RestController
@RequestMapping("/an/h5")
public class H5Controller extends BaseController
{
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private IAnWechatUserService anWechatUserService;

    @PostMapping("/h5Login")
    public AjaxResult login(HttpServletRequest request, @RequestBody AnWechatUser anWechatUser)
    {
        AnWechatUser tmpAnWechatUser = getAnWechatUser(request);
        if (tmpAnWechatUser != null)
        {
            return AjaxResult.success(tmpAnWechatUser);
        }
        List<AnWechatUser> anWechatUserList = anWechatUserService.selectAnWechatUserByPhoneNumber(anWechatUser.getPhone());
        JSONObject object = new JSONObject();
        if (anWechatUserList.size() == 0)
        {
            anWechatUser.setCreateTime(DateUtils.getNowDate());
            anWechatUserService.insertAnWechatUser(anWechatUser);
            AnWechatUser tmpUser = anWechatUserService.selectAnWechatUserByWechatUserId(anWechatUser.getWechatUserId());
            UUID uuid = UUID.randomUUID();
            String token = uuid.toString();
            redisTemplate.opsForValue().set("user:" + token, JSON.toJSONString(tmpUser));
            object.put("token", token);
        }
        if (object.size() > 0)
        {
            return AjaxResult.success(object);
        }
        if (anWechatUserList.size() > 0)
        {
            UUID uuid = UUID.randomUUID();
            String token = uuid.toString();
            redisTemplate.opsForValue().set("user:" + token, JSON.toJSONString(anWechatUserList.get(0)));
            object.put("token", token);
            return AjaxResult.success(object);
        }
        return AjaxResult.success("失败！");
    }

    //获取微信小程序http连接地址
    @PostMapping("/getWechatUrl")
    public String getWechatUrl()
    {
        String access_token = HttpUtil.get("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appid + "&secret=" + secret);
        JSONObject jsonObject = JSON.parseObject(access_token);
        Map<String, Object> mData = new HashMap<>();
        mData.put("path", "pages/index/index");
        mData.put("query","");
        mData.put("expire_type", 1);
        mData.put("expire_interval", 30);
        String result = HttpUtil.post("https://api.weixin.qq.com/wxa/generate_urllink?access_token=" + jsonObject.get("access_token"), JSON.toJSONString(mData));
        JSONObject urlJsonObject = JSON.parseObject(result);
        if (urlJsonObject.get("errmsg").equals("ok"))
        {
            String wechatUrl = urlJsonObject.get("url_link").toString().replace("\\","");
            return wechatUrl;
        }
        return "";
    }


    private AnWechatUser getAnWechatUser(HttpServletRequest request) {
        String token = request.getParameter("token");
        if (StringUtils.isEmpty(token))
        {
            return null;
        }
        String string = redisTemplate.opsForValue().get("user:" + token);
        JSONObject object = JSONObject.parseObject(string);
        AnWechatUser anWechatUser = object.toJavaObject(AnWechatUser.class);
        return anWechatUser;
    }

}
